Count Univalue Subtrees

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

For example:

Given binary tree,

  1. 5
  2. / \
  3. 1 5
  4. / \ \
  5. 5 5 5

return 4.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. int count;
  12. public int countUnivalSubtrees(TreeNode root) {
  13. count = 0;
  14. helper(root);
  15. return count;
  16. }
  17. boolean helper(TreeNode root) {
  18. if (root == null)
  19. return true;
  20. boolean left = helper(root.left);
  21. boolean right = helper(root.right);
  22. if (left && right && (root.left == null || root.val == root.left.val) && (root.right == null || root.val == root.right.val)) {
  23. count++;
  24. return true;
  25. }
  26. return false;
  27. }
  28. }

Check Univalue Tree

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public boolean isUnivalTree(TreeNode root) {
  12. if (root == null)
  13. return false;
  14. return helper(root, root.val);
  15. }
  16. boolean helper(TreeNode root, in val) {
  17. if (root == null)
  18. return true;
  19. if (root.val != val)
  20. return false;
  21. return helper(root.left, val) && helper(root.right, val);
  22. }
  23. }